package com.hskn.hss.module.carviolation.service.impl;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hskn.hss.core.annotation.DataScope;
import com.hskn.hss.core.domain.BaseEntity;
import com.hskn.hss.core.page.TableDataInfo;
import com.hskn.hss.core.utils.LoginUtils;
import com.hskn.hss.exception.HssException;
import com.hskn.hss.module.carviolation.entity.CarViolation;
import com.hskn.hss.module.carviolation.entity.CarViolationCharts;
import com.hskn.hss.module.carviolation.mapper.CarViolationMapper;
import com.hskn.hss.module.carviolation.service.ICarViolationService;
import com.hskn.hss.module.carviolation.vo.CarViolationTableDetailVO;
import com.hskn.hss.module.messageFlowRecords.domain.MessageFlowRecords;
import com.hskn.hss.module.messageFlowRecords.service.IMessageFlowRecordsService;
import com.hskn.hss.module.tlcar.entity.TlCar;
import com.hskn.hss.module.tlcar.service.ITlCarService;
import com.hskn.hss.module.user.entity.User;
import com.hskn.hss.module.user.mapper.UserMapper;
import com.hskn.hss.module.violationHandleLog.domain.ViolationHandleLog;
import com.hskn.hss.module.violationHandleLog.service.IViolationHandleLogService;
import com.hskn.hss.utils.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author hskn
 * @since 2021-05-20
 */
@Service
public class CarViolationServiceImpl extends ServiceImpl<CarViolationMapper, CarViolation> implements ICarViolationService {

    @Resource
    private CarViolationMapper carViolationMapper;
    @Autowired
    private IViolationHandleLogService violationHandleLogService;
    @Resource
    UserMapper userMapper;
    @Autowired
    private ITlCarService carService;
    @Autowired
    public IMessageFlowRecordsService messageFlowRecordsService;
    @Autowired
    LocationUtils locationUtil;

    @Override
    @DataScope(deptAlias = "depid", userAlias = "deal_uid")
    public JSONObject mList(BaseEntity entity, JSONObject params) throws HssException {

        String uid = LoginUtils.getUser().getUid();
        JSONObject json = new JSONObject();
        QueryWrapper<CarViolation> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().orderByDesc(CarViolation::getCreateTime);
        if (entity.getParams().containsKey("dataScope")&&StringUtils.isNotEmpty(entity.getParams().get("dataScope"))) {
            queryWrapper.lambda().apply(entity.getParams().get("dataScope").toString());
        }
        String depid = params.getString("depid");
        if (StringUtils.isNotEmpty(depid)) {
            queryWrapper.lambda().eq(CarViolation::getDepid, depid);
        }
        String type = params.getString("type");
        if (StringUtils.isNotEmpty(type)) {
            queryWrapper.lambda().eq(CarViolation::getCarTypeName, type);
        }
        String carViolationId = params.getString("carViolationId");
        if (StringUtils.isNotEmpty(carViolationId)) {
            queryWrapper.lambda().eq(CarViolation::getCarViolationId, carViolationId);
        }
        String ruleTypeName = params.getString("ruleTypeName");
        if (StringUtils.isNotEmpty(ruleTypeName)) {
            queryWrapper.lambda().eq(CarViolation::getRuleTypeName, ruleTypeName);
        }
        String ruleTypeId = params.getString("ruleTypeId");
        if (StringUtils.isNotEmpty(ruleTypeId)) {
            queryWrapper.lambda().eq(CarViolation::getRuleTypeId, ruleTypeId);
        }
        String carTypeId = params.getString("carTypeId");
        if (StringUtils.isNotEmpty(carTypeId)) {
            queryWrapper.lambda().eq(CarViolation::getCarTypeId, carTypeId);
        }
        String carTypeName = params.getString("carTypeName");
        if (StringUtils.isNotEmpty(carTypeName)) {
            queryWrapper.lambda().like(CarViolation::getCarTypeName, carTypeName);
        }
        String carId = params.getString("carId");
        if (StringUtils.isNotEmpty(carId)) {
            queryWrapper.lambda().eq(CarViolation::getCarId, carId);
        }
        String module = params.getString("module");
        if (StringUtils.isNotEmpty(module)) {
            queryWrapper.lambda().eq(CarViolation::getModule, module);
        }
        String gridId = params.getString("gridId");
        if (StringUtils.isNotEmpty(gridId)) {
            queryWrapper.lambda().eq(CarViolation::getGridId, gridId);
        }
        String startDate = params.getString("startDate");
        String endDate = params.getString("endDate");
        if (StringUtils.isNotEmpty(startDate) && StringUtils.isNotEmpty(endDate)) {
            if (startDate.equals(endDate)) {
                queryWrapper.lambda().like(CarViolation::getTime, startDate);
            } else {
                queryWrapper.lambda().between(CarViolation::getTime, startDate + " 00:00:00.0", endDate + " 23:59:59.999");
            }
        }
        Long page = StringUtils.isEmpty(params.getLong("page")) ? 1 : params.getLong("page");
        Long size = StringUtils.isEmpty(params.getLong("size")) ? 10 : params.getLong("size");
        Page<CarViolation> carViolationPage = new Page<>(page, size, true);
        IPage<CarViolation> iPage = carViolationMapper.selectPage(carViolationPage, queryWrapper);
        List<CarViolation> list = iPage.getRecords();
        Map<String, TlCar> tlEmployeesMap = carService.getCarMap(new QueryWrapper<>());
        for (CarViolation dlbjViolation : list) {
            if (tlEmployeesMap.containsKey(dlbjViolation.getCarId())) {
                dlbjViolation.setCarHeadPortraitViolation(tlEmployeesMap.get(dlbjViolation.getCarId()).getCarpicture());
            }
            MessageFlowRecords messageFlowRecords = new MessageFlowRecords();
            messageFlowRecords.setMessageId(dlbjViolation.getCarViolationId());
            messageFlowRecords.setKind(2);
            messageFlowRecords.setSubjectType(2);
            messageFlowRecords.setUserId(uid);
            List<MessageFlowRecords> messageFlowRecords1 = messageFlowRecordsService.selectMessageFlowRecordsList(messageFlowRecords);
            if ((Objects.nonNull(messageFlowRecords1) && messageFlowRecords1.size() > 0) || dlbjViolation.getTime().compareTo(DateUtil.parseDateTime(AttributeUtils.timeCompletion(DateUtil.formatDate(new Date()), 's'))) < 0){
                dlbjViolation.setIsRead(1);
            } else {
                dlbjViolation.setIsRead(0);
            }
        }
        json.put("total", iPage.getTotal());
        json.put("size", iPage.getSize());
        json.put("pages", iPage.getPages());
        json.put("current", iPage.getCurrent());
        json.put("list", iPage.getRecords());
        return json;
    }

    @Override
    @DataScope(deptAlias = "depid", userAlias = "deal_uid")
    public JSONObject collectList(BaseEntity entity, JSONObject params) throws HssException {

        String uid = LoginUtils.getUser().getUid();
        JSONObject res = new JSONObject();
        Long page = (StringUtils.isEmpty(params.getLong("page")) || params.getLong("page") == 0) ? 1 : params.getLong("page");
        Long size = (StringUtils.isEmpty(params.getLong("size")) || params.getLong("size") == 0) ? 10 : params.getLong("size");
        params.put("offset", (page - 1) * size);
        params.put("limit", size);

        String depid = String.valueOf(params.get("depid"));
        if (StringUtils.isNotEmpty(depid)){
            params.put("depid", depid);
        }

        String date = String.valueOf(params.get("date"));
        if (StringUtils.isNotEmpty(date) && !"null".equals(date)){
            String startDate = AttributeUtils.timeCompletion(date, 's');
            String endDate = AttributeUtils.timeCompletion(date, 'e');

            params.put("startDate",startDate);
            params.put("endDate",endDate);
        }
        params.put("params", entity.getParams());
        List<Map<String, Object>> list = carViolationMapper.collectList(params);
        long count = carViolationMapper.collectListCount(params);
        res.put("list", list);
        res.put("total", count);
        res.put("current", page);
        res.put("pages", (int) Math.ceil(count / size));
        res.put("size", list.size());
        return res;
    }

    @Override
    public Map<String, Object> collectCount(JSONObject params) throws HssException {

        String uid = LoginUtils.getUser().getUid();
        String date = String.valueOf(params.get("date"));
        if (StringUtils.isNotEmpty(date)){
            String startDate = AttributeUtils.timeCompletion(date, 's');
            String endDate = AttributeUtils.timeCompletion(date, 'e');

            params.put("startDate",startDate);
            params.put("endDate",endDate);
        }
        Map<String, Object> count = carViolationMapper.collectCount(params);
        return count;
    }

    @Override
    @DataScope(deptAlias = "depid", userAlias = "deal_uid")
    public List<Map> countByDay(BaseEntity entity, JSONObject params) throws HssException {

        String uid = LoginUtils.getUser().getUid();
        QueryWrapper<CarViolation> carViolationQueryWrapper = new QueryWrapper<>();
        String carId = String.valueOf(params.get("carId"));
        if (StringUtils.isNotEmpty(carId)){
            carViolationQueryWrapper.lambda().in(CarViolation::getCarId, carId);
        }

        String depid = String.valueOf(params.get("depid"));
        if (StringUtils.isNotEmpty(depid)){
            carViolationQueryWrapper.lambda().in(CarViolation::getDepid, depid);
        }

        String ruleTypeName = String.valueOf(params.get("ruleTypeName"));
        if (StringUtils.isNotEmpty(ruleTypeName)){
            carViolationQueryWrapper.lambda().in(CarViolation::getRuleTypeName, ruleTypeName);
        }

//        String ruleTypeId = String.valueOf(params.get("ruleTypeId"));
//        if (StringUtils.isNotEmpty(ruleTypeId)){
//            carViolationQueryWrapper.lambda().in(CarViolation::getRuleTypeId, ruleTypeId);
//        }

        String carTypeId = String.valueOf(params.get("carTypeId"));
        if (StringUtils.isNotEmpty(carTypeId)){
            carViolationQueryWrapper.lambda().in(CarViolation::getCarTypeId, carTypeId);
        }

        String carTypeName = String.valueOf(params.get("carTypeName"));
        if (StringUtils.isNotEmpty(carTypeName)){
            carViolationQueryWrapper.lambda().in(CarViolation::getCarTypeName, carTypeName);
        }

        String gridId = String.valueOf(params.get("gridId"));
        if (StringUtils.isNotEmpty(gridId)){
            carViolationQueryWrapper.lambda().in(CarViolation::getGridId, gridId);
        }

        String module = String.valueOf(params.get("module"));
        if (StringUtils.isNotEmpty(module)){
            carViolationQueryWrapper.lambda().in(CarViolation::getModule, module);
        }

        String startDate = params.getString("startDate");
        String endDate = params.getString("endDate");
        if (StringUtils.isNotEmpty(startDate) && StringUtils.isNotEmpty(endDate)) {
            carViolationQueryWrapper.lambda().between(CarViolation::getTime, startDate, endDate);
        }
        if (entity.getParams().containsKey("dataScope")&&StringUtils.isNotEmpty(entity.getParams().get("dataScope"))) {
            carViolationQueryWrapper.lambda().apply(entity.getParams().get("dataScope").toString());
        }
        List<CarViolation> carViolations = carViolationMapper.selectList(carViolationQueryWrapper);
        carViolations.forEach(t->{
            t.setDate(DateUtil.formatDate(t.getTime()));
        });
        Map<String, List<CarViolation>> collect = carViolations.stream().collect(Collectors.groupingBy(CarViolation::getDate));

        List<Map> list = new ArrayList<>();
        collect.keySet().forEach(t->{
            List<CarViolation> carViolations1 = collect.get(t);
            Map map = new HashMap();
            map.put("date",t);
            map.put("count",carViolations1.size());
            list.add(map);
        });
        return list;
    }

    @Override
    public List<Map<String, Object>> histogram(JSONObject params) throws HssException {

        QueryWrapper<CarViolation> queryWrapper = new QueryWrapper<>();
        String ruleTypeName = params.getString("ruleTypeName");
        if (StringUtils.isNotEmpty(ruleTypeName)) {
            queryWrapper.lambda().eq(CarViolation::getRuleTypeName, ruleTypeName);
        }
        String depid = params.getString("depid");
        if (StringUtils.isNotEmpty(depid)) {
            queryWrapper.lambda().eq(CarViolation::getDepid, depid);
        }
        String ruleTypeId = params.getString("ruleTypeId");
        if (StringUtils.isNotEmpty(ruleTypeId)) {
            queryWrapper.lambda().eq(CarViolation::getRuleTypeId, ruleTypeId);
        }
        String carTypeId = params.getString("carTypeId");
        if (StringUtils.isNotEmpty(carTypeId)) {
            queryWrapper.lambda().eq(CarViolation::getCarTypeId, carTypeId);
        }
        String carTypeName = params.getString("carTypeName");
        if (StringUtils.isNotEmpty(carTypeName)) {
            queryWrapper.lambda().like(CarViolation::getCarTypeName, carTypeName);
        }
        String carId = params.getString("carId");
        if (StringUtils.isNotEmpty(carId)) {
            queryWrapper.lambda().eq(CarViolation::getCarId, carId);
        }
        String gridId = params.getString("gridId");
        if (StringUtils.isNotEmpty(gridId)) {
            queryWrapper.lambda().eq(CarViolation::getGridId, gridId);
        }
        String module = params.getString("module");
        if (StringUtils.isNotEmpty(module)) {
            queryWrapper.lambda().eq(CarViolation::getModule, module);
        }
        String startDate = params.getString("startDate");
        String endDate = params.getString("endDate");
        if (StringUtils.isNotEmpty(startDate) && StringUtils.isNotEmpty(endDate)) {
            queryWrapper.lambda().between(CarViolation::getTime, startDate, endDate);
        }
        queryWrapper.select("car_name, count(1) as count");
        queryWrapper.lambda().groupBy(CarViolation::getCarName);
        List<Map<String, Object>> list = listMaps(queryWrapper);
        return list;
    }

    @Override
    public List<Map<String, Object>> summaryByWglx(JSONObject params) throws HssException {
        QueryWrapper<CarViolation> queryWrapper = new QueryWrapper<>();
        String ruleTypeName = params.getString("ruleTypeName");
        if (StringUtils.isNotEmpty(ruleTypeName)) {
            queryWrapper.lambda().eq(CarViolation::getRuleTypeName, ruleTypeName);
        }
        String ruleTypeId = params.getString("ruleTypeId");
        if (StringUtils.isNotEmpty(ruleTypeId)) {
            queryWrapper.lambda().eq(CarViolation::getRuleTypeId, ruleTypeId);
        }
        String carTypeId = params.getString("carTypeId");
        if (StringUtils.isNotEmpty(carTypeId)) {
            queryWrapper.lambda().eq(CarViolation::getCarTypeId, carTypeId);
        }
        String carTypeName = params.getString("carTypeName");
        if (StringUtils.isNotEmpty(carTypeName)) {
            queryWrapper.lambda().like(CarViolation::getCarTypeName, carTypeName);
        }
        String carId = params.getString("carId");
        if (StringUtils.isNotEmpty(carId)) {
            queryWrapper.lambda().eq(CarViolation::getCarId, carId);
        }
        String gridId = params.getString("gridId");
        if (StringUtils.isNotEmpty(gridId)) {
            queryWrapper.lambda().eq(CarViolation::getGridId, gridId);
        }
        String module = params.getString("module");
        if (StringUtils.isNotEmpty(module)) {
            queryWrapper.lambda().eq(CarViolation::getModule, module);
        }
        String startDate = params.getString("startDate");
        String endDate = params.getString("endDate");
        if (StringUtils.isNotEmpty(startDate) && StringUtils.isNotEmpty(endDate)) {
            queryWrapper.lambda().between(CarViolation::getTime, startDate, endDate);
        }
        int count = carViolationMapper.selectCount(queryWrapper);
        queryWrapper.select("rule_type_name, count(1) as count");
        queryWrapper.lambda().groupBy(CarViolation::getRuleTypeName);
        List<Map<String, Object>> list = listMaps(queryWrapper);
        Map<String, Object> map = new HashMap<>();
        map.put("count", count);
        map.put("rule_type_name", "违规总数");
        list.add(map);

        long carCount = carViolationMapper.collectListCount(params);
        Map<String, Object> map2 = new HashMap<>();
        map2.put("count", carCount);
        map2.put("rule_type_name", "车辆数");
        list.add(map2);
        return list;
    }

    @Override
    @DataScope(deptAlias = "depid", userAlias = "deal_uid")
    public JSONObject summaryByWglxJson(BaseEntity entity, JSONObject params) throws HssException {
        QueryWrapper<CarViolation> queryWrapper = new QueryWrapper<>();
        String ruleTypeName = params.getString("ruleTypeName");
        if (StringUtils.isNotEmpty(ruleTypeName)) {
            queryWrapper.lambda().eq(CarViolation::getRuleTypeName, ruleTypeName);
        }
        String depid = params.getString("depid");
        if (StringUtils.isNotEmpty(depid)) {
            queryWrapper.lambda().eq(CarViolation::getDepid, depid);
        }
        String ruleTypeId = params.getString("ruleTypeId");
        if (StringUtils.isNotEmpty(ruleTypeId)) {
            queryWrapper.lambda().eq(CarViolation::getRuleTypeId, ruleTypeId);
        }
        String carTypeId = params.getString("carTypeId");
        if (StringUtils.isNotEmpty(carTypeId)) {
            queryWrapper.lambda().eq(CarViolation::getCarTypeId, carTypeId);
        }
        String carTypeName = params.getString("carTypeName");
        if (StringUtils.isNotEmpty(carTypeName)) {
            queryWrapper.lambda().like(CarViolation::getCarTypeName, carTypeName);
        }
        String carId = params.getString("carId");
        if (StringUtils.isNotEmpty(carId)) {
            queryWrapper.lambda().eq(CarViolation::getCarId, carId);
        }
        String gridId = params.getString("gridId");
        if (StringUtils.isNotEmpty(gridId)) {
            queryWrapper.lambda().eq(CarViolation::getGridId, gridId);
        }
        String module = params.getString("module");
        if (StringUtils.isNotEmpty(module)) {
            queryWrapper.lambda().eq(CarViolation::getModule, module);
        }
        String startDate = params.getString("startDate");
        String endDate = params.getString("endDate");
        if (StringUtils.isNotEmpty(startDate) && StringUtils.isNotEmpty(endDate)) {
            if (startDate.equals(endDate)) {
                queryWrapper.lambda().like(CarViolation::getTime, startDate);
            } else {
                queryWrapper.lambda().between(CarViolation::getTime, startDate, endDate);
            }
        }
        startDate = AttributeUtils.timeCompletion(startDate, 's');
        endDate = AttributeUtils.timeCompletion(endDate, 'e');

        params.put("startDate", startDate);
        params.put("endDate", endDate);

        params.put("params", entity.getParams());
        if (entity.getParams().containsKey("dataScope")&&StringUtils.isNotEmpty(entity.getParams().get("dataScope"))) {
            queryWrapper.lambda().apply(entity.getParams().get("dataScope").toString());
        }
        int count = carViolationMapper.selectCount(queryWrapper);
        long carCount = carViolationMapper.collectListCount(params);
        queryWrapper.select("rule_type_name, count(1) as count");
        queryWrapper.lambda().groupBy(CarViolation::getRuleTypeName);
        List<Map<String, Object>> list = listMaps(queryWrapper);
        JSONObject top1 = new JSONObject();
        top1.put("name", "");
        top1.put("count", 0);
        for (Map<String, Object> map : list) {
            if (Integer.parseInt(map.get("count").toString()) > top1.getIntValue("count")) {
                top1.put("name", map.get("rule_type_name"));
                top1.put("count", Integer.parseInt(map.get("count").toString()));
            }
        }
        JSONObject json = new JSONObject();
        json.put("vCount", count);
        json.put("carCount", carCount);
        json.put("pie", list);
        json.put("top1", top1);
        return json;
    }

    @Override
    public void deal(JSONObject params) throws HssException {

        String uid = LoginUtils.getUser().getUid();
        if (StringUtils.isEmpty(params) || StringUtils.isEmpty(params.getString("carViolationIds"))) {
            throw new HssException("参数错误");
        }
        String carViolationIdStr = params.getString("carViolationIds");
        String[] carViolationIds = carViolationIdStr.split(",");
        QueryWrapper<CarViolation> dlbjViolationQueryWrapper = new QueryWrapper<>();
        dlbjViolationQueryWrapper.lambda().in(CarViolation::getCarViolationId, carViolationIds);
        List<CarViolation> carViolationList = carViolationMapper.selectList(dlbjViolationQueryWrapper);
        Map<String, CarViolation> carViolationMap = null;
        if (!carViolationList.isEmpty()) {
            carViolationMap = GroupingByUtils.getGroupingForMapEntity(carViolationList,
                    CarViolation::getCarViolationId, Collectors.collectingAndThen(Collectors.toList(), value -> value.get(0)));
        } else {
            carViolationMap = new HashMap<>();
        }
        User user = userMapper.selectById(uid);
        List<CarViolation> carViolations = new ArrayList<>();
        List<ViolationHandleLog> violationHandleLogList = new LinkedList<>();
        ViolationHandleLog violationHandleLog = null;
        CarViolation violation = null;
        for (String carViolationId : carViolationIds) {
            CarViolation carViolation = new CarViolation(carViolationId, params.getString("dealType"), uid, params.getString("dealRemark"));
            carViolations.add(carViolation);
            if (carViolationMap.containsKey(carViolationId)) {
                violation = carViolationMap.get(carViolationId);
                violationHandleLog = getViolationHandleLog(violation, params, uid, user);
                violationHandleLogList.add(violationHandleLog);
            }


        }
        violationHandleLogService.saveBatch(violationHandleLogList);
        updateBatchById(carViolations);
    }

    private ViolationHandleLog getViolationHandleLog(CarViolation violation, JSONObject params, String uid, User user) {
        ViolationHandleLog violationHandleLog = new ViolationHandleLog(
                StringUtils.uuid(), violation.getCarViolationId(), violation.getCarId(), violation.getCarName(), violation.getCarTypeId(), violation.getCarTypeName(), new Date(), violation.getDepid()
                , violation.getDepName(), violation.getCarTypeId(), violation.getRuleTypeName(), params.getString("dealType"), uid,
                user != null ? user.getName() : "", params.getString("dealRemark"), violation.getContent(), violation.getViolationStartTime(),
                violation.getViolationEndTime(), violation.getIsKeep(), violation.getLng(), violation.getLat(), violation.getTime(), violation.getAddress()
                , "0", "car"
        );
        return violationHandleLog;
    }


    @Override
    public List<List<Object>> selectCarViolationForCharts(CarViolation carViolation) throws ParseException {
        if (Objects.isNull(carViolation.getViolationStartTime())){
            carViolation.setViolationStartTime(DateUtil.parseDateTime(DateUtil.format(new Date(), DatePattern.NORM_MONTH_PATTERN)+"-01 00:00:00"));
        } else {
            carViolation.setViolationStartTime(DateUtil.parseDateTime(DateUtil.formatDate(carViolation.getViolationStartTime()) +" 00:00:00"));
        }
        if (Objects.isNull(carViolation.getViolationEndTime())){
            carViolation.setViolationEndTime(DateUtil.parseDateTime(DateUtil.formatDate(new Date())+" 23:59:59"));
        } else {
            carViolation.setViolationEndTime(DateUtil.parseDateTime(DateUtil.formatDate(carViolation.getViolationEndTime())+" 23:59:59"));
        }
        Date startDate = carViolation.getViolationStartTime();
        Date endDate = carViolation.getViolationEndTime();
        List<CarViolationCharts> bTableList = carViolationMapper.selectCarViolationForCharts(carViolation);

        if (Objects.nonNull(bTableList) && bTableList.size()>0){
            QueryWrapper<CarViolation> carViolationQueryWrapper=new QueryWrapper<>();
            if (StringUtils.isNotEmpty(carViolation.getCarId())){
                carViolationQueryWrapper.lambda().eq(CarViolation::getCarId,carViolation.getCarId());
            }
            if (StringUtils.isNotEmpty(carViolation.getCarName())){
                carViolationQueryWrapper.lambda().eq(CarViolation::getCarName,carViolation.getCarName());
            }
            if (StringUtils.isNotEmpty(carViolation.getRuleTypeName())){
                carViolationQueryWrapper.lambda().eq(CarViolation::getRuleTypeName,carViolation.getRuleTypeName());
            }
            if ("2".equals(carViolation.getDateType())){
                carViolationQueryWrapper.lambda().ge(CarViolation::getTime,bTableList.get(0).getTime() + "-01 00:00:00");
                carViolationQueryWrapper.lambda().le(CarViolation::getTime,bTableList.get(bTableList.size()-1).getTime() + "-31 23:59:59");
            } else {
                carViolationQueryWrapper.lambda().ge(CarViolation::getTime,bTableList.get(0).getTime() + " 00:00:00");
                carViolationQueryWrapper.lambda().le(CarViolation::getTime,bTableList.get(bTableList.size()-1).getTime() + " 23:59:59");
            }

            List<CarViolation> carViolationList = carViolationMapper.selectList(carViolationQueryWrapper);

            if ("2".equals(carViolation.getDateType())){
                carViolationList.forEach(t->{
                    t.setDate(DateUtil.format(t.getTime(),DatePattern.NORM_MONTH_PATTERN));
                });
            } else {
                carViolationList.forEach(t->{
                    t.setDate(DateUtil.formatDate(t.getTime()));
                });
            }

            Map<String, List<CarViolation>> carViolationMap = carViolationList.stream().collect(Collectors.groupingBy(CarViolation::getDate));

            Map<String, Map<String, List<CarViolation>>> map2 = new HashMap<>();
            carViolationMap.keySet().forEach(t->{
                List<CarViolation> carViolations = carViolationMap.get(t);
                Map<String, List<CarViolation>> alarmTypeCarMap = carViolations.stream().collect(Collectors.groupingBy(CarViolation::getRuleTypeName));
                map2.put(carViolations.get(0).getDate(),alarmTypeCarMap);
            });

            for (CarViolationCharts carViolationCharts:bTableList
            ) {
                if (Objects.nonNull(map2) && map2.size() > 0){
                    if (Objects.nonNull(map2.get(carViolationCharts.getTime()).get("车辆停留"))){
                        carViolationCharts.setCltlCount(map2.get(carViolationCharts.getTime()).get("车辆停留").size());
                    }
                    if (Objects.nonNull(map2.get(carViolationCharts.getTime()).get("车辆空驶"))){
                        carViolationCharts.setClksCount(map2.get(carViolationCharts.getTime()).get("车辆空驶").size());
                    }
                    if (Objects.nonNull(map2.get(carViolationCharts.getTime()).get("速度限制"))){
                        carViolationCharts.setSdxzCount(map2.get(carViolationCharts.getTime()).get("速度限制").size());
                    }
                }
            }
        }
        if ("2".equals(carViolation.getDateType())){
            return getSelectAlarmForChartsByMonth(startDate, endDate, bTableList);
        } else {
            return getSelectAlarmForCharts(startDate, endDate, bTableList);
        }
    }

    @Override
    public List<CarViolationCharts> selectCarViolationForTable(CarViolation carViolation) {
        if (Objects.isNull(carViolation.getViolationStartTime())){
            carViolation.setViolationStartTime(DateUtil.parseDateTime(DateUtil.format(new Date(), DatePattern.NORM_MONTH_PATTERN)+"-01 00:00:00"));
        } else {
            carViolation.setViolationStartTime(DateUtil.parseDateTime(DateUtil.formatDate(carViolation.getViolationStartTime()) +" 00:00:00"));
        }
        if (Objects.isNull(carViolation.getViolationEndTime())){
            carViolation.setViolationEndTime(DateUtil.parseDateTime(DateUtil.formatDate(new Date())+" 23:59:59"));
        } else {
            carViolation.setViolationEndTime(DateUtil.parseDateTime(DateUtil.formatDate(carViolation.getViolationEndTime())+" 23:59:59"));
        }
        List<CarViolationCharts> carViolationChartsList = carViolationMapper.selectCarViolationForTable(carViolation);
        if (Objects.nonNull(carViolationChartsList) && carViolationChartsList.size()>0){
            QueryWrapper<CarViolation> carViolationQueryWrapper=new QueryWrapper<>();
            if (StringUtils.isNotEmpty(carViolation.getCarId())){
                carViolationQueryWrapper.lambda().eq(CarViolation::getCarId,carViolation.getCarId());
            }
            if (StringUtils.isNotEmpty(carViolation.getCarName())){
                carViolationQueryWrapper.lambda().eq(CarViolation::getCarName,carViolation.getCarName());
            }
            if (StringUtils.isNotEmpty(carViolation.getRuleTypeName())){
                carViolationQueryWrapper.lambda().eq(CarViolation::getRuleTypeName,carViolation.getRuleTypeName());
            }

            carViolationQueryWrapper.lambda().ge(CarViolation::getTime,carViolation.getViolationStartTime());
            carViolationQueryWrapper.lambda().le(CarViolation::getTime,carViolation.getViolationEndTime());

            List<CarViolation> carViolationList = carViolationMapper.selectList(carViolationQueryWrapper);

            carViolationList.forEach(t->{
                t.setDate(DateUtil.formatDate(t.getTime()));
            });
            Map<String, List<CarViolation>> carViolationMap = carViolationList.stream().collect(Collectors.groupingBy(CarViolation::getCarName));

            Map<String, Map<String, List<CarViolation>>> map2 = new HashMap<>();
            carViolationMap.keySet().forEach(t->{
                List<CarViolation> carViolations = carViolationMap.get(t);
                Map<String, List<CarViolation>> alarmTypeCarMap = carViolations.stream().collect(Collectors.groupingBy(CarViolation::getRuleTypeName));
                map2.put(carViolations.get(0).getCarName(),alarmTypeCarMap);
            });

            for (CarViolationCharts carViolationCharts:carViolationChartsList
            ) {
                if (Objects.nonNull(map2.get(carViolationCharts.getCarName()).get("车辆停驶"))){
                    carViolationCharts.setCltlCount(map2.get(carViolationCharts.getCarName()).get("车辆停驶").size());
                }
                if (Objects.nonNull(map2.get(carViolationCharts.getCarName()).get("车辆空驶"))){
                    carViolationCharts.setClksCount(map2.get(carViolationCharts.getCarName()).get("车辆空驶").size());
                }
                if (Objects.nonNull(map2.get(carViolationCharts.getCarName()).get("速度限制"))){
                    carViolationCharts.setSdxzCount(map2.get(carViolationCharts.getCarName()).get("速度限制").size());
                }
            }
        }
        return carViolationChartsList;
    }


    private  List<List<Object>> getSelectAlarmForCharts(Date startDate,Date endDate,List<CarViolationCharts> bTableList) throws ParseException {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        List<Object> resList = new ArrayList<>();
        List<List<Object>> resList2 = new ArrayList<>();
        List<String> dateStringList = new ArrayList<>();
        dateStringList = Tools.getDateList(format, startDate, endDate);
        Boolean flag = true;
        for (int i = 0; i < dateStringList.size(); i++) {
            resList.add(dateStringList.get(i));
            for (CarViolationCharts c : bTableList) {
                if (dateStringList.get(i).equals(c.getTime())) {
                    flag = false;
                    resList.addAll(c.getResList());
                    resList2.add(resList);
                }
            }
            for (CarViolationCharts c : bTableList) {
                if (flag) {
                    resList.add(0);
                    resList.add(0);
                    resList.add(0);
                    resList.add(0);
                    resList2.add(resList);
                    flag = false;
                }
            }

            resList = new ArrayList<>();
            flag = true;

        }
        return resList2;
    }
    private  List<List<Object>> getSelectAlarmForChartsByMonth(Date startDate,Date endDate,List<CarViolationCharts> bTableList) throws ParseException {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM");
        List<Object> resList = new ArrayList<>();
        List<List<Object>> resList2 = new ArrayList<>();
        List<String> dateStringList = new ArrayList<>();

        String beginDate =  DateUtil.formatDate(startDate);
        String lastDate = DateUtil.formatDate(endDate);
        dateStringList = Tools.getMonthList(beginDate, lastDate);
        Boolean flag = true;
        for (int i = 0; i < dateStringList.size(); i++) {
            resList.add(dateStringList.get(i));
            for (CarViolationCharts c : bTableList) {
                if (dateStringList.get(i).equals(c.getTime())) {
                    flag = false;
                    resList.addAll(c.getResList());
                    resList2.add(resList);
                }
            }
            for (CarViolationCharts c : bTableList) {
                if (flag) {
                    resList.add(0);
                    resList.add(0);
                    resList.add(0);
                    resList.add(0);
                    resList2.add(resList);
                    flag = false;
                }
            }

            resList = new ArrayList<>();
            flag = true;

        }
        return resList2;
    }


    /**
     * 列表明细
     */
    @Override
    public TableDataInfo selectCarViolationForTableDetail(CarViolation carViolation) {
        if (Objects.isNull(carViolation.getViolationStartTime())){
            carViolation.setViolationStartTime(DateUtil.parseDateTime(DateUtil.format(new Date(), DatePattern.NORM_MONTH_PATTERN)+"-01 00:00:00"));
        } else {
            carViolation.setViolationStartTime(DateUtil.parseDateTime(DateUtil.formatDate(carViolation.getViolationStartTime()) +" 00:00:00"));
        }
        if (Objects.isNull(carViolation.getViolationEndTime())){
            carViolation.setViolationEndTime(DateUtil.parseDateTime(DateUtil.formatDate(new Date())+" 23:59:59"));
        } else {
            carViolation.setViolationEndTime(DateUtil.parseDateTime(DateUtil.formatDate(carViolation.getViolationEndTime())+" 23:59:59"));
        }
        QueryWrapper<CarViolation> carViolationQueryWrapper=new QueryWrapper<>();
        if (StringUtils.isNotEmpty(carViolation.getCarId())){
            carViolationQueryWrapper.lambda().eq(CarViolation::getCarId,carViolation.getCarId());
        }
        if (StringUtils.isNotEmpty(carViolation.getCarName())){
            carViolationQueryWrapper.lambda().eq(CarViolation::getCarName,carViolation.getCarName());
        }
        if (StringUtils.isNotEmpty(carViolation.getRuleTypeName())){
            carViolationQueryWrapper.lambda().eq(CarViolation::getRuleTypeName,carViolation.getRuleTypeName());
        }

        carViolationQueryWrapper.lambda().eq(CarViolation::getCarId,carViolation.getCarId());
        carViolationQueryWrapper.lambda().ge(CarViolation::getTime,carViolation.getViolationStartTime());
        carViolationQueryWrapper.lambda().le(CarViolation::getTime,carViolation.getViolationEndTime());
        carViolationQueryWrapper.lambda().orderByDesc(CarViolation::getTime);

        List<CarViolation> carViolationList = carViolationMapper.selectList(carViolationQueryWrapper);

        List<CarViolationTableDetailVO> carViolationTableDetailVOList = new ArrayList<>();
        carViolationList.forEach(t -> {
            CarViolationTableDetailVO carViolationTableDetailVO = new CarViolationTableDetailVO();
            carViolationTableDetailVO.setCarId(t.getCarId());
            carViolationTableDetailVO.setCarName(t.getCarName());
            carViolationTableDetailVO.setCarTypeName(t.getCarTypeName());
            carViolationTableDetailVO.setDepName(t.getDepName());
            carViolationTableDetailVO.setRuleTypeName(t.getRuleTypeName());
            carViolationTableDetailVO.setViolationStartTime(DateUtil.formatDateTime(t.getViolationStartTime()));
            carViolationTableDetailVO.setViolationEndTime(DateUtil.formatDateTime(t.getViolationEndTime()));
            carViolationTableDetailVO.setContent(t.getContent());
            /** 保存地址 **/
            String currentAddress = locationUtil.getAddress(t.getLng(), t.getLat());
            if (StringUtils.isNotEmpty(currentAddress)) {
                carViolationTableDetailVO.setAddress(currentAddress);
            } else {
                carViolationTableDetailVO.setAddress("");
            }
            carViolationTableDetailVOList.add(carViolationTableDetailVO);
        });
        return Tools.buildTableDataInfo(carViolation.getPageNum(), carViolation.getPageSize(), carViolationTableDetailVOList);
    }
}